package com.yizhe.controller;

import com.kangli.base.web.controller.BaseSpringMvcMybatisController;
import com.kangli.base.web.controller.bean.UploadFile;
import com.yizhe.utils.DateUtils4KL;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * @author Xu,ZhengYang
 */
public class BaseController extends BaseSpringMvcMybatisController implements ApplicationContextAware {

	
	@Autowired
	protected ApplicationContext context;

	/**
	 * @param request
	 * @return 获取请求项目地址
	 */
	public String getCtxPath(HttpServletRequest request) {
		StringBuffer ctx = new StringBuffer();
		ctx.append(request.getScheme()).append("://").append(request.getServerName()).append(":").append(request.getServerPort());
		ctx.append(request.getContextPath());

		return ctx.toString();
	}
	
	protected <T> T getService(Class<T> clazz) {
		return this.context.getBean(clazz);
	}
	
	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * @author Cheng,Zhi
	 * @desc 设置token
	 */
	protected void setToken(HttpServletRequest request) {
		request.getSession(false).setAttribute("token", UUID.randomUUID().toString());
	}

	/**
	 * @author Cheng,Zhi
	 * @desc 清除token
	 */
	protected void removeToken(HttpServletRequest request) {
		request.getSession(false).removeAttribute("token");
	}

	/**
	 * @author Cheng,Zhi
	 * @desc 是否重复提交
	 */
	protected boolean isRepeatSubmit(HttpServletRequest request) {
		String serverToken = (String) request.getSession(false).getAttribute("token");
		if (serverToken == null) {
			return true;
		}
		String clinetToken = request.getParameter("token");
		if (clinetToken == null) {
			return true;
		}
		if (!serverToken.equals(clinetToken)) {
			return true;
		}
		return false;
	}

	/**
	 * @param request
	 * @return 获取请求服务地址，不包括服务名
	 */
	public String getCtxPortPath(HttpServletRequest request) {
		StringBuffer ctx = new StringBuffer();
		ctx.append(request.getScheme()).append("://").append(request.getServerName()).append(":").append(request.getServerPort());
		return ctx.toString();
	}

	/**
	 * 取tomcat webapps目录
	 * 
	 * @param request
	 * @return
	 */
	public static String getTomcatWebappsPath(HttpServletRequest request) {
		String tomcatRoot = request.getSession().getServletContext().getRealPath("/");
		String project_name = request.getContextPath();

		if ("".equals(project_name)) {
			project_name = "/ROOT";
		}
		String webapps = tomcatRoot.replace("\\", "/").replace(project_name + "/", "");

		return webapps;
	}

	/**
	 * 处理NULL值 如果不为null,返回原值，如果为NULL，返回str
	 */
	public String handleNull(Object obj, String ifnull) {
		return (null == obj) ? ifnull : obj.toString();
	}

	public String handleNull(Object obj, String ifnull, String notnull) {

		if (StringUtils.isBlank(ifnull)) {
			ifnull = "";
		}

		String return_str = (null == obj) ? ifnull : (StringUtils.isNotBlank(notnull) ? notnull : obj.toString());
		return return_str;
	}

	// 针对日期字段
	public String handleNull(Date obj, String ifnull, String pattern) {
		if (StringUtils.isBlank(ifnull)) {
			ifnull = "";
		}

		String return_str = (null == obj) ? ifnull : DateUtils4KL.fomatDate(obj, pattern);
		return return_str;
	}

	protected List<UploadFile> uploadFilethis(HttpServletRequest request, String uploadDir) throws Exception {
		if (StringUtils.indexOf(request.getContentType(), "multipart/form-data") == -1) {
			return null;
		}

		if (StringUtils.isBlank(uploadDir)) {
			uploadDir = StringUtils.join(new String[] { "sktPicture", "picture", "" }, File.separator);
		}

		String[] folderPatterns = { "yyyy", "MM", "dd", "" };
		String autoCreatedDateDir = DateFormatUtils.format(new Date(), StringUtils.join(folderPatterns, File.separator));
		String ctxDir = getTomcatWebappsPath(request);// request.getServletContext().getRealPath(File.separator);
		if (!ctxDir.endsWith(File.separator)) {
			ctxDir = ctxDir + File.separator;
		}
		File savePath = new File(ctxDir + uploadDir + autoCreatedDateDir);
		this.logger.debug("===> save path is: {}", savePath);
		if (!savePath.exists()) {
			savePath.mkdirs();
		}

		List<UploadFile> uploadFileList = new ArrayList<UploadFile>();
		UploadFile uploadFile = null;

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

		Iterator<String> names = multipartRequest.getFileNames();

		while (names.hasNext()) {
			List<MultipartFile> files = multipartRequest.getFiles(names.next());

			for (MultipartFile mfile : files) {
				String fileName = mfile.getOriginalFilename().trim();
				if (!"".equals(fileName)) {
					uploadFile = new UploadFile();
					uploadFile.setContentType(mfile.getContentType());
					uploadFile.setFileSize(mfile.getSize());
					uploadFile.setFileName(mfile.getOriginalFilename().toString());
					uploadFile.setFormName(mfile.getName().trim());

					String fileSaveName = StringUtils.join(new String[] { UUID.randomUUID().toString(), ".", uploadFile.getExtension() });

					String port = this.getCtxPortPath(request) + "/";
					String fileSavePath = uploadDir + autoCreatedDateDir + fileSaveName;
					uploadFile.setFileSaveName(fileSaveName);
					uploadFile.setFileSavePath(port + StringUtils.replace(fileSavePath, File.separator, "/"));
					this.logger.debug(uploadFile.toString());
					uploadFileList.add(uploadFile);

					InputStream ins = mfile.getInputStream();
					OutputStream os = new FileOutputStream(ctxDir + fileSavePath);
					int bytesRead = 0;
					byte[] buffer = new byte[8192];
					while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
						os.write(buffer, 0, bytesRead);
					}

					os.close();
					ins.close();
				}
			}
		}
		return uploadFileList;
	}

	public void setApplicationContext(ApplicationContext arg0)
			throws BeansException {
		// TODO Auto-generated method stub
		this.context = arg0;
	}
}
